
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
-- =============================================
-- Author:		LAXMAN S
-- Create date: 06-05-2012
-- Description:	Creating Customer
-- =============================================
CREATE PROCEDURE [lgw].[usp_Customer_Address_Create] 
(
    
            @in_CustomerId bigint
           ,@in_FirstName nvarchar(50)
           ,@in_LastName nvarchar(50)
           ,@in_MiddleName nvarchar(20)
           ,@in_AddressTypeid bigint
           ,@in_Address1 nvarchar(50)
           ,@in_Address2 nvarchar(50)
           ,@in_City nvarchar(50)
           ,@in_State nvarchar(50)
           ,@in_Country nvarchar(50)
           ,@in_Zip1 nvarchar(50)
           ,@in_Zip2 nvarchar(50)
           ,@in_isPrimary bit
           ,@in_CreatedUser nvarchar(25)
            ,@in_UpdatedUser nvarchar(50)
          )
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

BEGIN TRY

     DECLARE @lv_InsertedId BIGINT
	CREATE TABLE #Temp(Id BIGINT)
BEGIN TRAN
	
	UPDATE [lgw].[Customer_Address] SET isPrimary=0 WHERE [CustomerId]=@in_CustomerId
	
INSERT INTO [lgw].[Customer_Address]
           ([CustomerId]
           ,[FirstName]
           ,[LastName]
           ,[MiddleName]
           ,[AddressTypeid]
           ,[Address1]
           ,[Address2]
           ,[City]
           ,[State]
           ,[Country]
           ,[Zip1]
           ,[Zip2]
           ,[isPrimary]
           ,[CreatedUser]
           ,[UpdatedUser]
           )  OUTPUT INSERTED.AddressId INTO #Temp
     VALUES
           (@in_CustomerId 
           ,@in_FirstName
           ,@in_LastName
           ,@in_MiddleName
           ,@in_AddressTypeid 
           ,@in_Address1 
           ,@in_Address2 
           ,@in_City
           ,@in_State 
           ,@in_Country 
           ,@in_Zip1 
           ,@in_Zip2  
           ,@in_isPrimary 
           ,@in_CreatedUser 
           ,@in_UpdatedUser  
          )
IF @@ERROR <> 0
      BEGIN
        RAISERROR(N'Error While Creating Address', 16, 0);
      END
SELECT @lv_InsertedId=Id FROM #Temp

END TRY			
BEGIN CATCH 
	RETURN -99
END CATCH
IF @lv_InsertedId >0
BEGIN 
	COMMIT
END
ELSE BEGIN
	ROLLBACK
END

RETURN @lv_InsertedId
END


GO
